<template>
  <div class="game">
    <div class="spinner">
      <div class="dot1"></div>
      <div class="dot2"></div>
    </div>
    <div class="spinner-text">资源加载中
      <br>{{progress.toFixed()}}%</div>
    <div :is="frame_stage"
         :player="player"
         :room="room"></div>
  </div>
</template>

<script>
import Empty from "./stage/Empty";
import Home from "./stage/Home.js";
import WaitGamer from "./stage/WaitGamer.js";
import Gaming from "./stage/Gaming.js";
import WaitEndGame from "./stage/WaitEndGame.js";
import EndGame from "./stage/EndGame.js";
import {
  ROOM_STATUS,
  PLAYER_STATUS
} from '../STATUS';
export default {
  name: 'game',
  components: {
    Empty,
    Home,
    WaitGamer,
    Gaming,
    WaitEndGame,
    EndGame,
  },
  data() {
    return {
      progress: 0,
      player: {
        info: {
          username: "",
          headimgurl: "",
          cards: 0,
          points: 0,
          source_cards: 0,
          fake: true
        },
        status: 0,
        actions: []
      },
      frame_stage: "empty",
      room: {
        id: "",
        status: 0,
        owner: null,
        players: [],
        data: null,
      },
      stage: "home",
      player_list: [],
      data_ready: false,
      room_setting: {},
    }
  },
  created() {
    if (window.socket) {
      socket.destroy();
    }
    window.socket = io(server_href);
    let wx_code
    if (query.u) {
      wx_code = query.u;
      localStorage.setItem("wx-login-code", wx_code);
      const new_query = Object.assign({}, query);
      delete new_query.u;
      location.href = `http://${location.host}${location.pathname}?${queryString.stringify(new_query)}`
      return
    }
    if (!wx_code) {
      wx_code = localStorage.getItem("wx-login-code")
    }
    if (!wx_code) {
      wx_code = Math.random().toString(36).substr(2, 6);
    }
    socket.on("try-wx-login", () => {
      window.wxLoginGetUserInfo();
    });
    socket.on("reconnect", () => {
      socket.emit("user-login", { wx_code });
      socket.once("user-login-success", (player) => {
        this.player = player;
        // 生产分享码
      });
    });
    socket.emit("user-login", { wx_code });
    socket.once("user-login-success", (player) => {
      Raven.setUserContext(Object.assign({}, player.info, {
        id: player.id
      }));
      // this.player = player;
      var before_ready = 2;
      for (let emit_key of ["player-frame", "room-frame"]) {
        socket.once(emit_key, () => {
          console.log(before_ready);
          before_ready -= 1;
          if (before_ready === 0) {
            this.data_ready = true;
            for (let watch_key of ["room.status", "player.status"]) {
              this.$watch(watch_key, function (status) {
                console.log(watch_key, status);
                const player_status = this.player.status;
                const room_status = this.room.status;
                if (room_status === ROOM_STATUS.COM_SCORES || (room_status === ROOM_STATUS.SHOW_SCORES && player_status === PLAYER_STATUS.AFTER_SUBMIT)) {
                  this.frame_stage = "end-game"
                }
                if (player_status === PLAYER_STATUS.AFTER_SUBMIT && room_status !== ROOM_STATUS.SHOW_SCORES) {
                  this.frame_stage = "wait-end-game"
                }
              }, { immediate: true })
            }
          }
        });
      }

      socket.on("room-frame", (room_frame) => {
        console.log("room-frame", room_frame);
        this.room = room_frame;
      });
      socket.on("player-frame", (player_frame) => {
        console.log("player-frame", player_frame);
        if (this.room_setting.pre_room_use_card === 0) {
          const player_info = player_frame.info;
          player_info.source_cards = player_info.cards;
          player_info.cards = "无限";//免费模式
        }
        this.player = player_frame;
      });
      socket.once("player-frame", () => {
        this.$watch("player.status", function (status) {
          console.log("player.status", status)
          if (status === PLAYER_STATUS.FREE) {
            this.frame_stage = "home"
          }
          if (status === PLAYER_STATUS.UN_READY || status === PLAYER_STATUS.READY) {
            this.frame_stage = "wait-gamer"
          }
          if (status === PLAYER_STATUS.BEFORE_SUBMIT) {
            this.frame_stage = "gaming"
          }
        }, { immediate: true });
      });

      socket.emit("room-setting")// 获取房间基本设置
      socket.on("room-setting", room_setting => {
        this.room_setting = room_setting;
        const player_info = this.player.info;
        let changed = false;
        if (this.room_setting.pre_room_use_card === 0) {
          if (player_info.cards !== "无限") {
            player_info.source_cards = player_info.cards;
            player_info.cards = "无限";//免费模式
            changed = true;
          }
        } else {
          if (player_info.cards === "无限") {
            player_info.cards = player_info.source_cards;
            changed = true;
          }
        }
        if (changed) {
          this.player.info = Object.assign({}, player_info);
        }
      });
      window.vm = this;

      // if (!player.info.fake) {
      //   document.body.ontouchstart = () => {
      //     // if (!window.bgm) {
      //     window.bgm = new Howl({
      //       // src: [resource_href + "sound/BEIJING.mp3", resource_href + "sound/BEIJING.ogg"],
      //       src: ["./static/BEIJING.mp3", "./static/BEIJING.ogg"],
      //       html5: true,
      //       loop: true,
      //     });
      //     // }
      //     bgm.play();
      //     document.body.ontouchstart = null;
      //   };
      //   if (!isMobile.apple.device) {
      //     document.body.ontouchstart();
      //   }
      //   // bgm.play();
      // }

      wx_promise.then(wx => {
        const query = queryString.parse();
        console.log("player", player, query)
        query.share_code = player.id;
        const new_query = Object.assign({}, query);
        delete new_query.u;
        const wx_share_config = window._wx_onMenuShareAppMessage_config = {
          title: '闽游十三水', // 分享标题
          desc: '最正宗的闽南十三水，不用下载即点即玩', // 分享描述
          link: `http://${location.host}${location.pathname}?${queryString.stringify(new_query)}`, // 分享链接
          imgUrl: `http://${location.host}/static/logo.128x128.png`, // 分享图标
          type: '', // 分享类型,music、video或link，不填默认为link
          dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
          success: function () {
            // 用户确认分享后执行的回调函数
            // alert("share success")
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
            // alert("share error")
          }
        };
        wx.onMenuShareAppMessage(wx_share_config);

        window._wx_onMenuShareTimeline_config = {
          title: '闽游十三水，休闲时间自由匹配赚取水豆，兑换手机话费！', // 分享标题
          link: wx_share_config.link, // 分享链接
          imgUrl: wx_share_config.imgUrl, // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        };
        wx.onMenuShareTimeline(window._wx_onMenuShareTimeline_config);
      });
      // history.replaceState(null, '闽游十三水', '?' + queryString.stringify(query));
    });
    socket.on("res-error", err => {
      console.error("SERVER ERROR:", err.msg);
      alert(err.msg);
    });
    socket.on("alert-notice", notice_str => {
      console.info("SERVER NOTICE:", notice_str);
      alert(notice_str);
    });
    console.log("ok!!")
  },
  watch: {
    "room.data"(data) {
      data instanceof Array && data.forEach((results) => {
        const room = this.room;
        if (results && results.player_id) {
          for (let player of room.players) {
            if (player.id === results.player_id) {
              results.player = player;
              break;
            }
          }
          if (results.one_vs_one_list) {
            results.one_vs_one_list.forEach(one_vs_one => {
              for (let player of room.players) {
                if (player.id === one_vs_one.player_id) {
                  one_vs_one.player = player;
                  break;
                }
              }
            })
          }
        }
      });
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style >
.game {
  width: 100%;
  height: 100%;
  background: rgba(5, 52, 36, 0.79);
  /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#32a046+1,053424+100&0.6+1,0.79+100 */
  background: -moz-radial-gradient(center, ellipse cover, rgba(50, 160, 70, 0.6) 1%, rgba(5, 52, 36, 0.79) 100%);
  /* FF3.6-15 */
  background: -webkit-radial-gradient(center, ellipse cover, rgba(50, 160, 70, 0.6) 1%, rgba(5, 52, 36, 0.79) 100%);
  /* Chrome10-25,Safari5.1-6 */
  background: radial-gradient(ellipse at center, rgba(50, 160, 70, 0.6) 1%, rgba(5, 52, 36, 0.79) 100%);
  /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
}

.stage-component{
  width: 100%;
  height: 100%;
}

.spinner-text {
  width: 100%;
  height: 90px;
  /*position: relative;*/
  text-align: center;
  /*屏幕居中*/
  position: fixed;
  top: 50%;
  margin-top: -4em;
  font-size: 2em;
}

.spinner {
  /*加载动画*/
  /*margin: 100px auto;*/
  /*margin: 100px auto;*/
  width: 90px;
  height: 90px;
  /*position: relative;*/
  text-align: center;
  /*屏幕居中*/
  position: fixed;
  left: 50%;
  margin-left: -45px;
  top: 50%;
  margin-top: -45px;

  animation: rotate 2.0s infinite linear;
}

.dot1,
.dot2 {
  width: 60%;
  height: 60%;
  display: inline-block;
  position: absolute;
  top: 0;
  /*background-color: #67CF22;*/
  background-color: #6b0000;
  box-shadow: 0px 0 5px 0px #3a3a3a;
  border-radius: 100%;

  -webkit-animation: bounce 2.0s infinite ease-in-out;
  animation: bounce 2.0s infinite ease-in-out;
}

.dot2 {
  top: auto;
  bottom: 0px;
  -webkit-animation-delay: -1.0s;
  animation-delay: -1.0s;
}

@-webkit-keyframes rotate {
  100% {
    -webkit-transform: rotate(360deg)
  }
}

@keyframes rotate {
  100% {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg)
  }
}

@-webkit-keyframes bounce {
  0%,
  100% {
    -webkit-transform: scale(0.0)
  }
  50% {
    -webkit-transform: scale(1.0)
  }
}

@keyframes bounce {
  0%,
  100% {
    transform: scale(0.0);
    -webkit-transform: scale(0.0);
  }
  50% {
    transform: scale(1.0);
    -webkit-transform: scale(1.0);
  }
}

canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  animation: fadeIn 0.5s forwards;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.pixi-canvas-input {
  position: absolute;
  z-index: 11;
  background: none;
  padding: 0;
  margin: 0;
  border: 0;
}
</style>
